package com.server.common.security.code.utils.files;

import com.server.common.code.error.BusinessException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtils {

    /**
     * File转换MultipartFile
     * @author LXC
     * @date 2022/5/9 8:38
     */
    public static MultipartFile getMultipartFile(File file,String mediaType) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , mediaType
                , false
                , file.getName());
        try {
            InputStream input = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new BusinessException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }
}
